package com.wg.dome;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wg.common.ioc.WgIoc;
import com.wg.common.net.OperationRequest;
import com.wg.common.net.OperationResponse;
import com.wg.common.net.SendParameters;
import com.wg.dome.handle.BaseHandle;
import com.wg.net.*;
import com.wg.net.operations.InitRequest;

public class ClientPeer extends BasePeer {
    private static final Log log = LogFactory.get();
    private final DomeApplication application;
    private long playerId;


    public ClientPeer(InitRequest initRequest, DomeApplication application) {
        super(initRequest);
        this.application = application;
    }

    public void setPlayerId(long playerId) {
        this.playerId = playerId;
    }

    public long getPlayerId() {
        return playerId;
    }

    public DomeApplication getApplication() {
        return application;
    }

    @Override
    protected void onDisconnect(DisconnectReason reasonCode, String reasonDetail) {
        log.info("onDisconnect:{}", this.getConnectionId());
        application.getChatLobby().onRemoveAllChannel(this);
    }

    @Override
    protected void onOperationRequest(OperationRequest request, SendParameters sendParameters) {
        final long startExecTime = System.nanoTime();

        String handleName = "";
        OperationResponse response = null;
        try {
            HandleRequestMgr handleRequestMgr = WgIoc.get(HandleRequestMgr.class);
            BaseHandle handle = handleRequestMgr.getRequest(request.getOperationCode());
            if (handle == null) {
                response = ErrorHelper.getErrorResponse(request.getOperationCode(), ErrorCode.OPERATION_UNKNOWN);
            } else {
                response = handle.execute(this, request, sendParameters);
                handleName = handle.getClass().getSimpleName();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = ErrorHelper.getErrorResponse(request.getOperationCode(), ErrorCode.INNER_ERROR);
        } finally {
            if (response != null) {
                sendOperationResponse(response, sendParameters);
                if (response.getReturnCode() != 0) {
                    log.error("handle request({}), errorcode={} errdbsg={}",
                            request.getOperationCode(), response.getReturnCode(), response.getDebugMessage());
                }
            }
            final long endExecuteTime = System.nanoTime();
            log.info("handle request({}:{}), exe={} ms", request.getOperationCode(), handleName, (endExecuteTime - startExecTime) / 100_0000F);
        }
    }
}
